﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace PDX.ChangeTracking
{
    public class ChangeTracker
    {
        public Editor Target { get; private set; }
        public IChangeRecorder Recorder { get; private set; }

        object lastValue;

        public ChangeTracker(Editor editor, IChangeRecorder recorder)
        {
            this.Target = editor;
            this.Recorder = recorder;

            editor.GotKeyboardFocus += new System.Windows.Input.KeyboardFocusChangedEventHandler(editor_GotKeyboardFocus);
            editor.LostKeyboardFocus += new System.Windows.Input.KeyboardFocusChangedEventHandler(editor_LostKeyboardFocus);
        }

        void editor_GotKeyboardFocus(object sender, System.Windows.Input.KeyboardFocusChangedEventArgs e)
        {
            var pm = Context.GetPropertyModel(Target) as IPropertyModel;
            if (pm != null)
            {
                var value = pm.Value;
                lastValue = value;
            }
        }

        void editor_LostKeyboardFocus(object sender, System.Windows.Input.KeyboardFocusChangedEventArgs e)
        {
            var pm = Context.GetPropertyModel(Target) as IPropertyModel;
            if (pm != null)
            {
                var value = pm.Value;
                if (!object.Equals(lastValue, value))
                {
                    var change = new Change(pm, Target, lastValue, value, e.OldFocus);
                    Recorder.Record(change);
                    lastValue = value;
                }
            }
        }
    }
}
